package com.cqsw.bbs.controller;

import com.cqsw.bbs.bean.CreateImage;
import com.cqsw.bbs.bean.ErrorView;
import com.cqsw.bbs.entity.User;
import com.cqsw.bbs.service.UserService;
import com.cqsw.bbs.utils.FileUtil;
import com.cqsw.bbs.utils.Verification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: ZackYoung
 * @time: 2020/6/8
 */
@Controller
public class FileController {
    @Value("${file.path}")
    private String filePath;
    @Value("${file.img.nophoto}")
    private String nophoto;
    @Autowired
    private UserService userService;


    //    @RequestMapping("/picShow/{picName:.+}")
//    public void picShow(HttpServletResponse response, @PathVariable(name = "picName") String picName) throws IOException {
//        String imgPath = filePath + "img/";
//        String imagePath = imgPath + picName;
//        response.reset();
//        //判断文件是否存在
//        File file = new File(imagePath);
//        if (!file.exists()) {
//            imagePath = imgPath + nophoto;
//        }
//        // 得到输出流
//        OutputStream output = response.getOutputStream();
//        if (imagePath.toLowerCase().endsWith(".jpg"))// 使用编码处理文件流的情况：
//        {
//            response.setContentType("image/jpeg;charset=GB2312");// 设定输出的类型
//            // 得到图片的真实路径
//            // 得到图片的文件流
//            InputStream imageIn = new FileInputStream(new File(imagePath));
//            // 得到输入的编码器，将文件流进行jpg格式编码
//            JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(imageIn);
//            // 得到编码后的图片对象
//            BufferedImage image = decoder.decodeAsBufferedImage();
//            // 得到输出的编码器
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
//            encoder.encode(image);// 对图片进行输出编码
//            imageIn.close();// 关闭文件流
//        }
//        output.close();
//    }
    @RequestMapping(value = "uploadimage", method = RequestMethod.POST)
    @ResponseBody
    public Map upload(MultipartFile file) throws IOException {
        Map map = new HashMap();
        String imgPath = filePath + "img/";

        if (file.isEmpty()) {
            map.put("success", false);
            map.put("msg", "请选择图片");
        } else {
            String fileName = file.getOriginalFilename();
            File file1 = new File(imgPath + fileName);
            file.transferTo(file1);
            map.put("success", true);
            map.put("file_path","/bbs/picShow/"+fileName);
        }
        return map;
    }

    @RequestMapping(value = "/user/control/updateAvatar", method = RequestMethod.POST)
    @ResponseBody
    public Map upload(@RequestParam("file") MultipartFile file, HttpServletRequest request)
            throws IllegalStateException, IOException {
        CreateImage fileManage = new CreateImage();
        Map<String, String> error = new HashMap<String, String>();//错误

        String _width = request.getParameter("width");
        String _height = request.getParameter("height");
        String _x = request.getParameter("x");
        String _y = request.getParameter("y");


        Integer width = null;//宽
        Integer height = null;//高
        Integer x = 0;//坐标X轴
        Integer y = 0;//坐标Y轴

        // 判断文件是否为空，空则返回失败页面
        if (file.isEmpty()) {
            error.put("success", "false");
            return error;
        }


        if (_width != null && !"".equals(_width.trim())) {
            if (Verification.isPositiveInteger(_width.trim())) {
                if (_width.trim().length() >= 8) {
                    error.put("width", ErrorView._1200.name());//不能超过8位数字
                } else {
                    width = Integer.parseInt(_width.trim());
                }


            } else {
                error.put("width", ErrorView._1210.name());//宽度必须大于0
            }

        }
        if (_height != null && !"".equals(_height.trim())) {
            if (Verification.isPositiveInteger(_height.trim())) {
                if (_height.trim().length() >= 8) {
                    error.put("height", ErrorView._1200.name());//不能超过8位数字
                } else {
                    height = Integer.parseInt(_height.trim());
                }

            } else {
                error.put("height", ErrorView._1230.name());//高度必须大于0
            }
        }

        if (_x != null && !"".equals(_x.trim())) {
            if (Verification.isPositiveIntegerZero(_x.trim())) {
                if (_x.trim().length() >= 8) {
                    error.put("x", ErrorView._1200.name());//不能超过8位数字
                } else {
                    x = Integer.parseInt(_x.trim());
                }

            } else {
                error.put("x", ErrorView._1250.name());//X轴必须大于或等于0
            }

        }

        if (_y != null && !"".equals(_y.trim())) {
            if (Verification.isPositiveIntegerZero(_y.trim())) {
                if (_y.trim().length() >= 8) {
                    error.put("y", ErrorView._1200.name());//不能超过8位数字
                } else {
                    y = Integer.parseInt(_y.trim());
                }

            } else {
                error.put("y", ErrorView._1270.name());//Y轴必须大于或等于0
            }

        }

        // 获取原文件名
        String fileName = file.getOriginalFilename();
        //取得文件后缀
        String suffix = FileUtil.getExtension(fileName).toLowerCase();
        // 获取文件存储路径（绝对路径）
        String path = filePath + "img/";
        // 修改文件名
        String newName = FileUtil.renameImg() + "." + suffix;
        //生成200*200缩略图
        fileManage.createImage(file.getInputStream(), path + newName, suffix, x, y, width, height, 200, 200);
        // 数据库修改
        User user = (User) request.getSession().getAttribute("userList");
        int result = userService.updateAvatar(newName, user.getId());
        if (result > 0) {
            // 删除原图片

            File file1 = new File(path + user.getAvatarname());
            // 路径为文件且不为空则进行删除
            if (file1.isFile() && file1.exists()) {
                file1.delete();// 文件删除
            }
            user.setAvatarname(newName);

            error.put("success", "true");
        }
        return error;
    }

}
